package com.yiwei.zhh.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zhh.R;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.HuaKouBean;
import com.yiwei.zhh.api.callback.PaySelectContract;
import com.yiwei.zhh.api.requestInfo.PaySelectRequest;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.constant.UserGlobal;
import com.yiwei.zhh.event.AlipayUserEvent;
import com.yiwei.zhh.model.DealBeforeV3Model;
import com.yiwei.zhh.model.HuaKouModel;
import com.yiwei.zhh.model.PayWayModel;
import com.yiwei.zhh.model.RepayModel;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ScacheUtil;
import com.yiwei.zhh.util.Spans;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.util.Util;
import com.yiwei.zhh.view.BankSelectDialog;
import com.yiwei.zhh.view.Dialog;
import com.yiwei.zhh.view.MyProgressView;
import com.yiwei.zhh.view.SelectCodeTypeDialog;
import com.yiwei.zhh.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3RepayMoneyNewActivity extends BaseActivity implements PaySelectContract.View {

    @BindView(R.id.layout_top_color)
    SuperButton layoutTopColor;
    @BindView(R.id.layout_top_color_sec)
    SuperButton layoutTopColorSec;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.progress_normal)
    MyProgressView progressNormal;
    @BindView(R.id.progress_yuqi)
    SuperButton progressYuqi;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.txt_borrow_date)
    TextView txtBorrowDate;
    @BindView(R.id.txt_repay_date)
    TextView txtRepayDate;
    @BindView(R.id.txt_yuqi_fee)
    TextView txtYuqiFee;
    @BindView(R.id.cb_all)
    ImageView cbAll;
    @BindView(R.id.btn_xuqi_question)
    ImageView btnXuqiQuestion;
    @BindView(R.id.btn_xuqi)
    TextView btnXuqi;
    @BindView(R.id.img_xuqi)
    ImageView imgXuqi;
    @BindView(R.id.cb_xuqi)
    ImageView cbXuqi;
    @BindView(R.id.layout_xujie)
    LinearLayout layoutXujie;
    @BindView(R.id.txt_benxi)
    TextView txtBenxi;
    @BindView(R.id.txt_need_pay)
    TextView txtNeedPay;
    @BindView(R.id.img_bank_icon)
    ImageView imgBankIcon;
    @BindView(R.id.txt_bankcard)
    TextView txtBankcard;
    @BindView(R.id.btn_bankcard)
    LinearLayout btnBankcard;
    @BindView(R.id.txt_bank_notice)
    TextView txtBankNotice;
    @BindView(R.id.txt_money_all)
    TextView txtMoneyAll;
    @BindView(R.id.btn_pay_money)
    SuperButton btnPayMoney;
    @BindView(R.id.btn_wechat_repay)
    TextView btnWechatRepay;
    private String selectWays = ALI_APP;
    private static final String ALI_APP = "ALI_APP";
    private static final String ACTION_REPAY = "REPAY";
    private static final String ACTION_RENEWAL = "RENEWAL";
    private Unbinder unbinder;
    private String ACTION = "REPAY";

    private boolean isYuqi = false;
    private String trueMoney;
    private RepayModel.DataBean totalData;
    //    private String xuqiTotal;
    private String bankcard;
    private PaySelectRequest api;
    private BankSelectDialog bankSelectDialog;
    private String bankcard_id;

    //还款
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repay_money_new_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {

        bankSelectDialog = new BankSelectDialog(this);
        bankSelectDialog.setOnSelect(new BankSelectDialog.OnSureListener() {
            @Override
            public void onSure(String id, String bank_card) {
                txtBankcard.setText(bank_card.substring(0, 3) + "****" + bank_card.substring(bank_card.length() - 4, bank_card.length()));
                bankcard = bank_card;
                bankcard_id = id;
                api.getRepayData(bankcard_id);
            }
        });


        api = PaySelectRequest.create();
        api.attachView(this);

        api.getRepayData(bankcard_id);
    }

    @Override
    protected void onDestroy() {

        api.detachView();
        api = null;
        ScacheUtil.clearTextLineCache();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        unbinder = null;
        super.onDestroy();


    }

    public void getHuaKou() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();

        HuaKouBean bean = new HuaKouBean();
        bean.deal_id = UserGlobal.getDealId();
        bean.bankcard_id = bankcard_id;
        Api.api_service.getHuaKou(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    // -1 - 无还款信息 0 - 还款失败、1 - 还款成功、2 - 还款审核中
                    switch (result.data.repay_staus) {
                        case "-1":

                            break;
                        case "0":
                            Util.startActivity(this, RepayFailActivity.class);
                            finish();
                            break;
                        case "1":
                            Dialog.showRepaySuccessDialog(this, new Dialog.DialogDefaultClickListener() {
                                @Override
                                public void confirm() {
                                    finish();
                                }

                                @Override
                                public void cancel() {
                                    finish();
                                }
                            });
                            break;
                        case "2":
                            Intent intent = new Intent(this, RepayStatusActivity.class);
                            intent.putExtra("need_money", trueMoney);
                            startActivity(intent);
                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                            finish();
                            break;
                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlipayUser(AlipayUserEvent msg) {
//        txtAlipay.setText(msg.user);
    }


    @OnClick({R.id.btn_bankcard, R.id.btn_wechat_repay, R.id.txt_right, R.id.btn_back, R.id.cb_all, R.id.btn_xuqi_question, R.id.btn_xuqi, R.id.cb_xuqi, R.id.btn_pay_money})

    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_wechat_repay:
//                Intent intent1 = new Intent(this, WebViewActivity.class);
//                intent1.putExtra("title", "微信还款");
//                intent1.putExtra("url", Const.WECHAT_REPAY_URL);
//                startActivity(intent1);
//                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                Intent intent = new Intent(V3RepayMoneyNewActivity.this, RepayQrcodeActivity.class);
                intent.putExtra("money", trueMoney);
                intent.putExtra("action", ACTION);
                intent.putExtra("deal_id", totalData.id);
                intent.putExtra("yuqi", totalData.impose_all_money_format.replace("￥", ""));
                intent.putExtra("pay_type", "1");

                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);

//                selectCodeTypeDialog.show();
                break;
            case R.id.txt_right:
                Util.startActivity(this, V3MyBorrowRecordActivity.class);
                break;
            case R.id.btn_bankcard:
                bankSelectDialog.show();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.cb_all:
                if (isYuqi) {
                    cbAll.setImageResource(R.mipmap.img_pay_check_red);

                } else {
                    cbAll.setImageResource(R.mipmap.img_pay_cb_open);
                }

                ACTION = ACTION_REPAY;
                cbXuqi.setImageResource(R.mipmap.img_pay_uncheck_repay);
                if (totalData != null) {
//                    txtNeedPay.setText(totalData.month_need_all_repay_money + "元");
//                    txtMoneyAll.setText(totalData.month_need_all_repay_money + "");
                    setMoneyData(false);
                }
                break;
            case R.id.btn_xuqi_question:
                Dialog.showDefaultV3Dialog(this, "续期还款", "续期还款是本平台对信用良好用户推出的快速续期的还款方式，续期成功将自动延长一个借款周期，请保持良好信用记录。",
                        "", "我知道了", new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {

                            }

                            @Override
                            public void cancel() {

                            }
                        });
                break;
            case R.id.btn_xuqi:
                Dialog.showDefaultV3Dialog(this, "续期还款", "续期还款是本平台对信用良好用户推出的快速续期的还款方式，续期成功将自动延长一个借款周期，请保持良好信用记录。",
                        "取消", "联系客服", new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                Util.startActivity(V3RepayMoneyNewActivity.this, WechatChatActivity.class);
                            }

                            @Override
                            public void cancel() {

                            }
                        });
                break;
            case R.id.cb_xuqi:
                if (isYuqi) {
                    cbXuqi.setImageResource(R.mipmap.img_pay_check_red);

                } else {
                    cbXuqi.setImageResource(R.mipmap.img_pay_cb_open);
                }
                ACTION = ACTION_RENEWAL;
                cbAll.setImageResource(R.mipmap.img_pay_uncheck_repay);
                txtBenxi.setText("(续期+逾期费用)");
                if (totalData != null) {
//                    txtNeedPay.setText(totalData.renewal_money + "元");
//                    txtMoneyAll.setText(totalData.renewal_money + "");
                    setMoneyData(true);
                }

                break;

            case R.id.btn_pay_money:
                if (totalData == null) {
                    api.getRepayData(bankcard_id);
                    return;
                }

                if (UI.toString(btnPayMoney).equals("点击扫一扫还款")) {
//                    Intent intent = new Intent(this, WebViewActivity.class);
//                    intent.putExtra("title", "微信还款");
//                    intent.putExtra("url", Const.WECHAT_REPAY_URL);
//                    startActivity(intent);
//                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    Intent intent1 = new Intent(V3RepayMoneyNewActivity.this, RepayQrcodeActivity.class);
                    intent1.putExtra("money", trueMoney);
                    intent1.putExtra("action", ACTION);
                    intent1.putExtra("deal_id", totalData.id);
                    intent1.putExtra("yuqi", totalData.impose_all_money_format.replace("￥", ""));
                    intent1.putExtra("pay_type", "1");

                    startActivity(intent1);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
//                    selectCodeTypeDialog.show();


                    return;
                }

                if (ACTION.equals(ACTION_RENEWAL)) {
                    api.getDealBefore();
                } else if (ACTION.equals(ACTION_REPAY)) {

                    Spanned txt_info = Spans.with(this).font(bankcard.substring(0, 3) + "****" + bankcard.substring(bankcard.length() - 4, bankcard.length()), getResources().getDimensionPixelSize(R.dimen.x40), 0xff27293E).
                            font("\n" + "为避免还款失败，请确认您要划扣的银行卡余额充足哦", getResources().getDimensionPixelSize(R.dimen.x30), 0xffB6BCDB).
                            build();
                    Dialog.showV3DefaultDialog(this, "提示", txt_info, "取消", "确定", new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getHuaKou();
                        }

                        @Override
                        public void cancel() {

                        }
                    });


                }


                break;
        }
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        loadingDialog.dismiss();
    }

    @Override
    public void onRequestStart() {
        loadingDialog.show();
    }


    @Override
    public void getRepayDataSuccess(RepayModel item) {
        if (item == null || item.data == null) {
            return;
        }
        totalData = item.data;
        txtBorrowDate.setText("借款日期\n" + item.getData().repay_start_time);
        txtRepayDate.setText("还款日期\n" + item.getData().repay_end_time);
        txtYuqiFee.setText("逾期费用\n" + item.getData().impose_all_money_format);
        txtTips.setText("还款倒计时(天)");
        if (item.data.impose_day > 0) {
            txtTips.setText("已逾期时长(天)");
            progressYuqi.setVisibility(View.VISIBLE);
            progressYuqi.setText(item.data.impose_day + "");
            progressNormal.setVisibility(View.GONE);
            btnPayMoney.setShapeSolidColor(0xffFF5D5B).setUseShape();
//            txtTipsBottom.setVisibility(View.VISIBLE);
            txtBenxi.setText("(本息+逾期费用)");
            layoutTopColor.setVisibility(View.GONE);
            layoutTopColorSec.setVisibility(View.VISIBLE);
            isYuqi = true;

        } else {
            progressNormal.setProgressSec(Float.valueOf(item.data.remaining_days), Float.valueOf(item.data.repay_time_format.replace("天", "")));
            txtTips.setText("还款倒计时(天)");
            progressNormal.setVisibility(View.VISIBLE);
            txtTime.setText(item.data.remaining_days + "");
            btnPayMoney.setShapeSolidColor(0xff4C81FF).setUseShape();

//            layoutTopColor.setShapeGradientStartColor(0xffFE7E6F).setShapeGradientEndColor(0xffFB494F).setShapeGradientOrientation(SuperButton.LEFT_RIGHT).setUseShape();
            progressYuqi.setVisibility(View.GONE);
//            txtTipsBottom.setVisibility(View.GONE);

            isYuqi = false;
        }
        txtMoney.setText(item.data.need_repay_money_format.replace("￥", ""));


        if (item.data.renewal_show.equals("0")) {
            layoutXujie.setVisibility(View.GONE);
        } else {
            layoutXujie.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(item.data.renewal_money) && Float.valueOf(item.data.renewal_money) != 0) {
            btnXuqi.setVisibility(View.GONE);
            imgXuqi.setVisibility(View.GONE);
            cbXuqi.setVisibility(View.VISIBLE);
        }

        if (isYuqi) {
            cbAll.setImageResource(R.mipmap.img_pay_check_red);

        } else {
            cbAll.setImageResource(R.mipmap.img_pay_cb_open);
        }
        ACTION = ACTION_REPAY;


        setMoneyData(false);

        if (item.data.bankcard == null) {
            return;
        }
        txtBankNotice.setText(item.data.bankcard.notice);
        bankcard_id = item.data.bankcard.id;
        bankcard = item.data.bankcard.bankcard;
        txtBankcard.setText(bankcard.substring(0, 3) + "****" + bankcard.substring(bankcard.length() - 4, bankcard.length()));
        //是否能划扣：0 - 否、1 - 是，如果为 0，需提示用户去重新绑卡
        if (item.data.bankcard.is_allow_cut == 0) {
            Dialog.showDefaultV3Dialog(this, "银行卡认证", "银行卡" + bankcard.substring(0, 3) + "****" + bankcard.substring(bankcard.length() - 4, bankcard.length()) + "未认证，无法进行划扣，请认证或选择另一张银行卡", "", "我知道了", new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Intent intent = new Intent(V3RepayMoneyNewActivity.this, BankIdentityActivity.class);
                    intent.putExtra("bank_id", item.data.bankcard.id);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
//                    Util.startActivity(V3RepayMoneyNewActivity.this, BankIdentityActivity.class);
                }

                @Override
                public void cancel() {

                }
            });
        } else {
            if (item.data.bankcard.can_daikou_today.equals("0")) {
                txtBankNotice.setTextColor(0xffFE5A59);
                btnPayMoney.setText("点击扫一扫还款");
                imgBankIcon.setImageResource(R.mipmap.img_repay_bankcard_uncheck);
            } else {
                txtBankNotice.setTextColor(0xffB6BCDB);
                imgBankIcon.setImageResource(R.mipmap.img_repay_bankcard);
                btnPayMoney.setText("立即支付");
            }


        }


    }

    @Override
    public void getDealBefore(DealBeforeV3Model item) {
        switch (item.data.step) {
            case 0:

                Spanned txt_info = Spans.with(this).font(bankcard.substring(0, 3) + "****" + bankcard.substring(bankcard.length() - 4, bankcard.length()), getResources().getDimensionPixelSize(R.dimen.x40), 0xff27293E).
                        font("\n" + "为避免还款失败，请确认您要划扣的银行卡余额充足哦", getResources().getDimensionPixelSize(R.dimen.x30), 0xffB6BCDB).
                        build();
                Dialog.showV3DefaultDialog(this, "提示", txt_info, "取消", "确定", new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        getHuaKou();
                    }

                    @Override
                    public void cancel() {

                    }
                });

                break;
            case 1:
//                api.getOneKeyIdentity();
                break;
            case 2:
                Dialog.needOtherData(this, new Dialog.DialogClickListener() {
                    @Override
                    public void confirm() {
                        if (item.data.uplists != null && item.data.uplists.size() != 0) {
                            Intent intent = new Intent();
                            switch (item.data.uplists.get(0).remark) {
                                case Const.IdentityType.yunyin:
                                    intent.setClass(V3RepayMoneyNewActivity.this, V3YunYingIdentityActivity.class);
                                    break;
                                case Const.IdentityType.contacts:
                                    intent.setClass(V3RepayMoneyNewActivity.this, V3AddressIdentityActivity.class);
                                    break;
                                case Const.IdentityType.realname:
                                    intent.setClass(V3RepayMoneyNewActivity.this, V3IdcardIdentityActivity.class);
                                    break;
                                case Const.IdentityType.taobao:
                                    intent.setClass(V3RepayMoneyNewActivity.this, V3TaobaoIdentityActivity.class);
                                    break;
                                case Const.IdentityType.face_detect:
                                    intent.setClass(V3RepayMoneyNewActivity.this, V3FaceIdentityOneActivity.class);
                                    break;
                                case Const.IdentityType.xuexin:
                                    intent.setClass(V3RepayMoneyNewActivity.this, V3XueXinIdentityActivity.class);
                                    break;
                            }
                            intent.putExtra(Const.KEY.SOME_IDENTITY_KEY, item.data.uplists);
                            startActivity(intent);
                            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                        }
                    }
                });
                break;
            case 3:
                Dialog.showDefaultV3Dialog(this, "提示", "您的认证资料正在更新中这可能需要几分钟的时间，请耐心等待", "", "我知道了", new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
        }
    }

    @Override
    public void getHuaKouSuccess(HuaKouModel item) {


    }

    private void setMoneyData(boolean isXuqi) {
        if (isXuqi) {
//            如果是续期的话
            if (isYuqi) {
//                如果是逾期的话，有逾期费
                trueMoney = totalData.renewal_money;
                txtBenxi.setText("(续期费+逾期费用)");
            } else {
                trueMoney = totalData.renewal_money;
                txtBenxi.setText("(续期费用)");
            }
        } else {
            //            如果不是续期的话
            if (isYuqi) {
                txtBenxi.setText("(本息+逾期费用)");
            } else {
                txtBenxi.setText("(本息)");
            }
            trueMoney = totalData.month_need_all_repay_money + "";
        }

        txtNeedPay.setText(trueMoney + "元");
        txtMoneyAll.setText(trueMoney + "");

    }

    public void getIndex() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        Api.api_service.getV3HomeIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }

                }).
                subscribe(result -> {
                    if (result.data.deal_status.status.equals("1") || result.data.deal_status.status.equals("2")) {
                        finish();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getIndex();
//        if (isGotoPay) {
//            isGotoPay = false;
//            api.getRepayDialog();
//        }
    }

}
